<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElButton, ElInput, ElSelect, ElOption, ElDialog, ElForm, ElFormItem, ElMessage, ElMessageBox, ElTag, ElCard, ElTransfer, ElSpace, ElSwitch } from 'element-plus'
import { Plus, Edit, Delete, Search, View, Document } from '@element-plus/icons-vue'
import { paperApi } from '@/api/modules/paper.api'
import { questionApi } from '@/api/modules/question.api'
import type { IPaper, PaperStatus } from '@shared/types/paper'
import type { IQuestion } from '@shared/types/question'
import { useCommonStore } from '@/store/common'

const commonStore = useCommonStore()
commonStore.header = '试卷管理'

// 响应式数据
const loading = ref(false)
const tableData = ref<IPaper[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 搜索条件
const searchForm = reactive({
  keyword: '',
  status: '',
  creator: ''
})

// 弹窗控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref<'create' | 'edit' | 'view'>('create')

// 表单数据
const paperForm = reactive<Partial<IPaper>>({
  paper_name: '',
  description: '',
  duration: 90,
  status: 'draft',
  question_list: []
})

// 表单验证规则
const formRules = {
  paper_name: [
    { required: true, message: '请输入试卷名称', trigger: 'blur' },
    { min: 2, max: 50, message: '试卷名称长度应在2-50字符之间', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入考试时长', trigger: 'blur' },
    { type: 'number', min: 10, max: 300, message: '考试时长应在10-300分钟之间', trigger: 'blur' }
  ],
  question_list: [
    { type: 'array', min: 1, message: '请至少选择一道试题', trigger: 'change' }
  ]
}

// 试题相关
const allQuestions = ref<IQuestion[]>([])
const questionTransferData = ref<{key: string, label: string, score: number}[]>([])
const selectedQuestions = ref<string[]>([])

// 表单引用
const formRef = ref()

// 状态选项
const statusOptions = [
  { label: '草稿', value: 'draft' },
  { label: '已发布', value: 'published' },
  { label: '已归档', value: 'archived' }
]

// 获取状态标签类型
const getStatusType = (status: PaperStatus) => {
  const statusMap = {
    draft: 'info',
    published: 'success',
    archived: 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: PaperStatus) => {
  const statusMap = {
    draft: '草稿',
    published: '已发布',
    archived: '已归档'
  }
  return statusMap[status] || '未知'
}

// 计算总分
const totalScore = computed(() => {
  return selectedQuestions.value.reduce((total, questionId) => {
    const question = allQuestions.value.find(q => q._id === questionId)
    return total + (question?.score || 0)
  }, 0)
})

// 获取试卷列表
const fetchPapers = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm
    }
    const response = await paperApi.getPaperList(params)
    tableData.value = response.data.data
    total.value = response.data.total_records
  } catch (error) {
    console.error('获取试卷列表失败:', error)
    ElMessage.error('获取试卷列表失败')
  } finally {
    loading.value = false
  }
}

// 获取所有试题（用于创建试卷时选择）
const fetchAllQuestions = async () => {
  try {
    const response = await questionApi.getQuestionList({ page: 1, pageSize: 1000 })
    allQuestions.value = response.data.data
    questionTransferData.value = allQuestions.value.map(q => ({
      key: q._id!,
      label: `[${q.type === 'judgement' ? '判断' : q.type === 'select' ? '单选' : '多选'}] ${q.content} (${q.score}分)`,
      score: q.score
    }))
  } catch (error) {
    console.error('获取试题列表失败:', error)
    ElMessage.error('获取试题列表失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPapers()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: '',
    creator: ''
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchPapers()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchPapers()
}

// 打开弹窗
const openDialog = (type: 'create' | 'edit' | 'view', paper?: IPaper) => {
  dialogType.value = type
  dialogVisible.value = true
  
  if (type === 'create') {
    dialogTitle.value = '创建试卷'
    Object.assign(paperForm, {
      paper_name: '',
      description: '',
      duration: 90,
      status: 'draft',
      question_list: []
    })
    selectedQuestions.value = []
  } else if (type === 'edit' && paper) {
    dialogTitle.value = '编辑试卷'
    Object.assign(paperForm, { ...paper })
    selectedQuestions.value = paper.question_list?.map(q => typeof q === 'string' ? q : q._id!) || []
  } else if (type === 'view' && paper) {
    dialogTitle.value = '试卷详情'
    Object.assign(paperForm, { ...paper })
    selectedQuestions.value = paper.question_list?.map(q => typeof q === 'string' ? q : q._id!) || []
  }
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
  formRef.value?.resetFields()
  selectedQuestions.value = []
}

// 保存试卷
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const paperData = {
      ...paperForm,
      question_list: selectedQuestions.value,
      total_score: totalScore.value
    }
    
    if (dialogType.value === 'create') {
      await paperApi.createPaper(paperData)
      ElMessage.success('试卷创建成功')
    } else {
      await paperApi.updatePaper(paperForm._id!, paperData)
      ElMessage.success('试卷更新成功')
    }
    
    closeDialog()
    fetchPapers()
  } catch (error) {
    console.error('保存试卷失败:', error)
    ElMessage.error('保存试卷失败')
  }
}

// 删除试卷
const handleDelete = async (paper: IPaper) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除试卷"${paper.paper_name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await paperApi.deletePaper(paper._id!)
    ElMessage.success('试卷删除成功')
    fetchPapers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除试卷失败:', error)
      ElMessage.error('删除试卷失败')
    }
  }
}

// 发布/归档试卷
const handleStatusChange = async (paper: IPaper, newStatus: PaperStatus) => {
  try {
    await paperApi.updatePaper(paper._id!, { status: newStatus })
    ElMessage.success(`试卷已${getStatusText(newStatus)}`)
    fetchPapers()
  } catch (error) {
    console.error('更新试卷状态失败:', error)
    ElMessage.error('更新试卷状态失败')
  }
}

// 预览试卷
const handlePreview = (paper: IPaper) => {
  openDialog('view', paper)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPapers()
  fetchAllQuestions()
})
</script>

<template>
  <div class="paper-page">
    <!-- 搜索区域 -->
    <ElCard class="search-card">
      <div class="search-form">
        <ElSpace wrap>
          <ElInput
            v-model="searchForm.keyword"
            placeholder="搜索试卷名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <Search />
            </template>
          </ElInput>
          
          <ElSelect
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <ElOption
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
          
          <ElButton type="primary" :icon="Search" @click="handleSearch">
            搜索
          </ElButton>
          
          <ElButton @click="handleReset">
            重置
          </ElButton>
          
          <ElButton type="primary" :icon="Plus" @click="openDialog('create')">
            创建试卷
          </ElButton>
        </ElSpace>
      </div>
    </ElCard>

    <!-- 表格区域 -->
    <ElCard class="table-card">
      <ElTable
        :data="tableData"
        :loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <ElTableColumn prop="paper_name" label="试卷名称"  />
        
        <ElTableColumn prop="question_count" label="题目数量" width="100">
          <template #default="{ row }">
            {{ Array.isArray(row.question_list) ? row.question_list.length : 0 }}
          </template>
        </ElTableColumn>
        
        <ElTableColumn prop="total_score" label="总分" width="80" />
        
        <ElTableColumn prop="duration" label="时长(分钟)" width="100" />
        
        <ElTableColumn prop="status" label="状态" width="100">
          <template #default="{ row }">
            <ElTag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </ElTag>
          </template>
        </ElTableColumn>
        
        <ElTableColumn prop="creator" label="创建者" width="120">
          <template #default="{ row }">
            {{ typeof row.creator === 'object' ? row.creator.username : row.creator }}
          </template>
        </ElTableColumn>
        
        <ElTableColumn prop="create_time" label="创建时间" width="150">
          <template #default="{ row }">
            {{ new Date(row.create_time).toLocaleString() }}
          </template>
        </ElTableColumn>
        
        <ElTableColumn label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <ElSpace>
              <ElButton
                type="primary"
                size="small"
                :icon="View"
                @click="handlePreview(row)"
              >
                预览
              </ElButton>
              
              <ElButton
                type="primary"
                size="small"
                :icon="Edit"
                @click="openDialog('edit', row)"
              >
                编辑
              </ElButton>
              
              <ElButton
                type="danger"
                size="small"
                :icon="Delete"
                @click="handleDelete(row)"
              >
                删除
              </ElButton>
            </ElSpace>
          </template>
        </ElTableColumn>
      </ElTable>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <ElPagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </ElCard>

    <!-- 创建/编辑弹窗 -->
    <ElDialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1000px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <ElForm
        ref="formRef"
        :model="paperForm"
        :rules="formRules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <ElFormItem label="试卷名称" prop="paper_name">
          <ElInput
            v-model="paperForm.paper_name"
            placeholder="请输入试卷名称"
            maxlength="50"
            show-word-limit
          />
        </ElFormItem>
        
        <ElFormItem label="试卷描述">
          <ElInput
            v-model="paperForm.description"
            type="textarea"
            placeholder="请输入试卷描述"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
        </ElFormItem>
        
        <ElFormItem label="考试时长" prop="duration">
          <ElInput
            v-model.number="paperForm.duration"
            type="number"
            placeholder="请输入考试时长(分钟)"
            style="width: 200px"
          >
            <template #append>分钟</template>
          </ElInput>
        </ElFormItem>
        
        <ElFormItem label="试卷状态" prop="status">
          <ElSelect v-model="paperForm.status" style="width: 200px">
            <ElOption
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </ElFormItem>
        
        <ElFormItem label="选择试题" prop="question_list">
          <div class="question-transfer">
            <ElTransfer
              v-model="selectedQuestions"
              :data="questionTransferData"
              :titles="['可选试题', '已选试题']"
              :button-texts="['移除', '选择']"
              :props="{ key: 'key', label: 'label' }"
              filterable
              filter-placeholder="搜索试题"
              style="text-align: left; display: inline-block"
            />
            <div class="score-info">
              <p>已选题目数：{{ selectedQuestions.length }}</p>
              <p>总分数：{{ totalScore }}</p>
            </div>
          </div>
        </ElFormItem>
      </ElForm>

      <template #footer v-if="dialogType !== 'view'">
        <ElSpace>
          <ElButton @click="closeDialog">取消</ElButton>
          <ElButton type="primary" @click="handleSave">保存</ElButton>
        </ElSpace>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.paper-page {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.question-transfer {
  width: 100%;
}

.score-info {
  margin-top: 10px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}

.score-info p {
  margin: 0;
  line-height: 1.5;
}

:deep(.el-transfer) {
  display: flex;
  align-items: center;
}

:deep(.el-transfer-panel) {
  width: 280px;
}
</style>